import { ValueAccessor, withFormControl } from "solid-form-context";
import { createMemo, JSX, splitProps } from "solid-js";
import { is_null_or_undefined } from "~/utils/object";

export interface JsonEditProps
  extends Omit<JSX.TextareaHTMLAttributes<HTMLTextAreaElement>, 'value'>,
    ValueAccessor<string> {}

export const JsonEdit = (props: JsonEditProps) => {
  const [local, rest] = splitProps(props, ["value", "onChange"]);

  const formattedJson = createMemo(() => {
    try {
      const parsed = is_null_or_undefined(local.value) ? "{}" : local.value;
      return JSON.stringify(JSON.parse(parsed), null, 2);
    } catch (error) {
      return local.value;
    }
  });

  const handleValueChanged = (changedValue: string) => {
    try{
        return JSON.stringify(JSON.parse(changedValue));
    }
    catch{
        return changedValue;
    }
  };

  return (
    <textarea
      value={formattedJson()}
      onChange={(e) => handleValueChanged(e.target.value)}
      {...rest}
    />
  );
};

export const FormJsonEdit = withFormControl(JsonEdit, {});
